package panda.transaction;

import panda.file.*;
import panda.buffer.*;
import panda.server.*;
import java.util.*;

public class BufferList {
	private Map<Block, Buffer> getBuf = new HashMap<Block, Buffer>();
	private List<Block> pinned = new ArrayList<Block>();
	private BufferManager bufferManager = Panda.getBufferManager();
	
	public Buffer getBuffer(Block blk) {
		return getBuf.get(blk);
	}
	
	public void pin(Block blk) {
		Buffer buf = bufferManager.pin(blk);
		getBuf.put(blk, buf);
		pinned.add(blk);
	}
    
	public Block pinNew(String filename, PageFormatter fmt) {
		try {
		    Buffer buf = bufferManager.pinNew(filename, fmt);
		    Block blk = buf.getBlock();
			getBuf.put(blk, buf);
			pinned.add(blk);
			
			return blk;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("pinNew error");
		}
		return null;
	}
	
	public void unpin(Block blk) {
		Buffer buf = getBuf.get(blk);
		bufferManager.unpin(buf);
		pinned.remove(blk);
		
		if (!pinned.contains(blk)) {
			getBuf.remove(blk);
		}
	}
	
	public void unpinAll() {
		for (Block tempBlk : pinned) {
			Buffer tempBuf = getBuf.get(tempBlk);
			bufferManager.unpin(tempBuf);
		}
		
		getBuf.clear();
		pinned.clear();
	}
 }